
// a2.cpp
//
// Second assignment for Advanced Multimedia Computing
//
// T. Kostelijk & F. Huizinga
//     0418889      0418862
//
////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <cv.h>
#include <highgui.h>



int summedAbsDiff(IplImage *img1, IplImage *img2, IplImage *dest){
    cvAbsDiff(img1, img2, dest);
    CvScalar s = cvSum(dest);
    return s.val[0] + s.val[1] + s.val[2];
}

int main(int argc, char *argv[])
{
    IplImage *frame1 = 0; 
    IplImage *frame2 = 0; 
    IplImage *frame1Region = 0;
    IplImage *frame2Region = 0;
    IplImage *dest = 0;
    int nrBooks = 3;
    CvSize[] regionCoords = {cvSize(72, 45), cvSize(46, 103), cvSize(157,153)}
    CvSize[] regionSizes = {cvSize(67, 21), cvSize(69,22), cvSize(94,40)}
    
    frame1=cvLoadImage(argv[1]);
    if(!frame1){
        printf("Could not load image file: %s\n",argv[1]);
        exit(0);
    }

    frame2=cvLoadImage(argv[2]);
    if(!frame2){
        printf("Could not load image file: %s\n",argv[2]);
        exit(0);
    }
    // draw rectangle over book 1
    //cvRectangle(frame1, cvPoint(x,y), cvPoint(x+dx, y+dy), CV_RGB(0,255,0), CV_FILLED);

    for (int i=0; i<nrBooks; i++) {
        int x = regionCoords[i].width;
        int y = regionCoords[i].height;
        int dx = regionSizes[i].width;
        int dy = regionSizes[i].height;
        
        // initialise regions 
        frame1Region = cvCreateImage(cvSize(dx, dy), frame1->depth, frame1->nChannels);
        frame2Region = cvCreateImage(cvSize(dx, dy), frame2->depth, frame2->nChannels);
        dest = cvCreateImage(cvSize(dx, dy), frame2->depth, frame2->nChannels);
        
        // substract pixels of the region in frame 1 & 2
        cvGetRectSubPix(frame1, frame1Region, cvPoint2D32f(x+0.5*dx, y + 0.5*dy));
        cvGetRectSubPix(frame2, frame2Region, cvPoint2D32f(x+0.5*dx, y + 0.5*dy));

        sabsdiff = summedAbsDiff(frame1Region, frame2Region, dest);
        // print summed absolute difference 
        printf("diff for book %d = %d\n", i, sabsdiff);
        // x+round(0.5*dx), y + round(0.5*dy)

    }

    // create a window
    cvNamedWindow("mainWin", CV_WINDOW_AUTOSIZE); 
    cvMoveWindow("mainWin", 100, 100);

    // show the image
    cvShowImage("mainWin", frame1 );
    cvWaitKey(0);

    cvShowImage("mainWin", frame1Region );
    cvWaitKey(0);

    cvShowImage("mainWin", frame2Region );
    cvWaitKey(0);

    cvShowImage("mainWin", dest);
    cvWaitKey(0);

    // release the memory
    cvReleaseImage(&frame1);
    cvReleaseImage(&frame2);
    cvReleaseImage(&frame1Region);
    cvReleaseImage(&frame2Region);
    cvReleaseImage(&dest);
    return 0;
}
